import React, { useImperativeHandle, useReducer, useMemo, useEffect, useRef } from 'react';
import { EditableExcelTableProps, EditableExcelTableRef } from './types/public';
import { TColumn } from '@/components/editable-excel-table';
import styles from './index.module.less';
import { TableContext } from './context';
import { tableReducer, createInitialState } from './reducer/tableReducer';
import { TableAction } from './reducer/types';
import { HeaderTools } from './layout/HeaderTools';
import { Header } from './layout/Header';
import { Body } from './layout/Body';
import { VirtualBody } from './layout/VirtualBody';
import { StatusBar } from './layout/StatusBar';
import { TopEditorBar } from './layout/TopEditorBar';
import { SheetTitle } from './layout/SheetTitle';
import { getI18n } from './i18n';
import { DEFAULT_COLUMN_WIDTH } from './constant';

export const EditableExcelTable = React.forwardRef(function EditableExcelTable<C extends TColumn = TColumn>(
    props: EditableExcelTableProps<C>,
    ref: React.Ref<EditableExcelTableRef<C>>
) {
    const { sheetData, i18n: i18nConfig, tableBodyContainerStyle, sheetTitle, sheetTitleStyle, headerActions } = props;
    const navigationTimeRef = useRef<number>(0);

    // 初始化国际化
    const i18n = useMemo(() => {
        const baseI18n = getI18n(i18nConfig?.locale);
        if (i18nConfig?.messages) {
            return { ...baseI18n, ...i18nConfig.messages };
        }
        return baseI18n;
    }, [i18nConfig]);

    // 添加序号列
    const enhancedSheetData = useMemo(() => {
        const indexColumn: TColumn = {
            title: i18n.indexColumnTitle,
            dataIndex: '__index__',
            width: 60,
            required: false,
            type: 'text',
        };

        return {
            columns: [indexColumn, ...sheetData.columns],
            data: sheetData.data.map((row, index) => ({
                ...row,
                __index__: String(index + 1),
            })),
        };
    }, [sheetData]);

    const [state, dispatch] = useReducer(tableReducer<C>, createInitialState<C>(enhancedSheetData));

    // 更新导航时间的函数
    const updateNavigationTime = () => {
        navigationTimeRef.current = Date.now();
    };

    useImperativeHandle(ref, () => ({
        getData: () => {
            // 返回原始数据，不包含序号列
            return {
                columns: state.sheetData.columns.slice(1) as C[], // 移除序号列
                data: state.sheetData.data.map((row) => {
                    const { __index__, ...rowData } = row as any;
                    return rowData as any;
                }),
            } as any;
        },
    }));

    const BodyComp = props.virtualization?.enabled ? VirtualBody : Body;

    const totalWidth = state.sheetData.columns
        .map((c) => c.width ?? DEFAULT_COLUMN_WIDTH)
        .reduce((total, b) => total + b, 0);

    return (
        <TableContext.Provider
            value={{
                state: state,
                dispatch: dispatch as React.Dispatch<TableAction<TColumn>>,
                i18n: i18n,
                editorRenderers: props.editorRenderers,
            }}
        >
            <div className={styles['editable-excel-table']}>
                <SheetTitle title={sheetTitle} style={sheetTitleStyle} />
                <HeaderTools headerActions={headerActions} onNavigation={updateNavigationTime} />

                <TopEditorBar key={JSON.stringify(state.editingCell || {}) + JSON.stringify(state.activeCell || {})} />
                <div className={styles['table__content-parent']}>
                    <div
                        className={styles['table__content']}
                        style={{
                            width: `max(${totalWidth + 20}px, 100%)`,
                        }}
                    >
                        <Header />
                        <BodyComp
                            editorRenderers={props.editorRenderers}
                            virtualization={props.virtualization}
                            tableBodyContainerStyle={tableBodyContainerStyle}
                            navigationTimeRef={navigationTimeRef}
                        />
                    </div>
                </div>
                <StatusBar />
            </div>
        </TableContext.Provider>
    );
});
